<template>
  <view>
    <view class="header">
      <text class="header-title" @click="completion"
        v-show="!isCompletionStatus || (isTextareaFocused && isOldPlan)">完成</text>
    </view>
    <view class="plan-date-box">
      <uni-datetime-picker v-model="selectorDate" @change="selectDate" uni-primary="#fba007">
        <view class="plan-date">{{date + ' ' + dateTime}}</view>
      </uni-datetime-picker>
    </view>
    <view class="plan-content-box" :style="{height: windowHeight + 'px'}">
      <scroll-view class="plan-content-container" scroll-y>
        <textarea class="plan-content" v-model="content" maxlength="10000" @focus="handleTextareaFocus"
          @blur="handleTextareaBlur" :style="{height: windowHeight + 'px'}"></textarea>
      </scroll-view>
    </view>
    <view class="footer" v-show="isCompletionStatus || (!isTextareaFocused && isOldPlan)">
      <image class="footer-icon" src="../../static/plan_icons/delete.png" @click="deletePlan"></image>
      <image class="footer-icon" src="../../static/plan_icons/write.png" @click="writePlan"></image>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  export default {
    computed: {
      ...mapState('m_user', ['userinfo'])
    },
    data() {
      return {
        // 日期选择器默认日期时间
        selectorDate: "",
        // 系统窗口高度
        windowHeight: 0,
        // 日期
        date: '',
        // 日期时间
        dateTime: '',
        // 计划内容
        content: '',
        // 历史计划
        oldPlan: {},
        // 是否是历史计划
        isOldPlan: false,
        // 历史计划索引值
        index: 0,
        // 文本框焦点状态
        isTextareaFocused: false,
        // 输入完成状态
        isCompletionStatus: false,
        // 用户是否点击了删除按钮
        isDelete: false
      };
    },
    onLoad(options) {
      // 获取当前系统的信息
      const sysInfo = uni.getSystemInfoSync()
      // 为 windowHeight 窗口可用高度动态赋值
      this.windowHeight = sysInfo.windowHeight - 142

      if (options.plan) {
        const plan = JSON.parse(decodeURIComponent(options.plan));
        const index = parseInt(options.index);
        this.oldPlan = plan
        this.date = plan.date
        this.dateTime = plan.dateTime
        this.content = plan.content
        this.isOldPlan = true
        this.isCompletionStatus = true
        this.index = options.index
      } else {
        this.getDateTime()
      }
    },
    // 页面卸载事件
    onUnload() {
      // 判断是否是通过返回按钮离开页面
      const pages = getCurrentPages();
      if (pages.length === 3 && !this.isDelete) {
        // 用户点击了返回按钮
        this.updatePlanList()
      }
    },
    methods: {
      ...mapMutations('m_user', ['updateUserPlanList']),
      // 日期选择成功事件
      selectDate(e) {
        this.selectorDate = e;
        // 转换日期时间格式
        const dateObj = new Date(e);
        const year = dateObj.getFullYear();
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        const formattedDate = `${year}年${month}月${day}日`;
        const timeWithoutSecond = dateObj.toTimeString().slice(0, 5);
        // 为界面上的日期赋值
        this.date = formattedDate
        this.dateTime = timeWithoutSecond
      },

      // 获取时间事件
      getDateTime() {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const date = currentDate.getDate();
        const hours = currentDate.getHours();
        const minutes = currentDate.getMinutes();
        const seconds = currentDate.getSeconds();

        // 格式 XX年XX月XX日
        const formattedDateOne = `${year}年${month}月${date}日`
        // 格式 XX-XX-XX
        const formattedDateTwo = `${year}-${month < 10 ? '0' + month : month}-${date < 10 ? '0' + date : date}`;
        //格式 00:00
        const formattedDateTimeOne = `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}`
        //格式 00:00:00
        const formattedDateTimeTwo =
          `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
        // 为页面上的日期赋值
        this.date = formattedDateOne
        this.dateTime = formattedDateTimeOne
        // 为日期选择器的日期赋值
        this.selectorDate = formattedDateTwo + ' ' + formattedDateTimeTwo
      },
      // 点击"完成"按钮事件
      completion() {
        this.isCompletionStatus = true
      },
      // 更新计划列表事件
      updatePlanList() {
        if (this.isOldPlan === true && this.oldPlan.content === this.content && this.oldPlan.date === this.date &&
          this
          .oldPlan.dateTime === this.dateTime) {
          return
        }
        if (this.isOldPlan === true && (this.oldPlan.content !== this.content || this.oldPlan.date !== this.date ||
            this
            .oldPlan.dateTime !== this.dateTime)) {
          this.deletePlanToServer()
        }
        if (this.content === '') return

        this.updatePlanToServer()
      },
      // 文本框获得焦点
      handleTextareaFocus() {
        this.isTextareaFocused = true;
        this.isCompletionStatus = false
      },
      // 文本框失去焦点
      handleTextareaBlur() {
        this.isTextareaFocused = false;
      },
      // 删除计划事件
      deletePlan() {
        uni.showModal({
          title: '提示',
          content: '确认删除计划吗？',
        }).then(res => {
          if (res[1].confirm) {
            // 用户点击确定
            if (this.isOldPlan === true) {
              this.deletePlanToServer()
            }
            this.isDelete = true
            uni.navigateBack({
              delta: 1,
            });
            return uni.$showMsg('删除计划成功')
          }
        })
      },
      // 调用更新计划接口
      async updatePlanToServer() {
        // 准备参数
        var token = uni.getStorageSync('token')
        const plan = {
          date: this.date,
          dateTime: this.dateTime,
          content: this.content,
        }
        const query = {
          token,
          plan,
        }
        const {
          data: res
        } = await uni.$http.post('/api/update/plan', query)
        if (res.meta.status !== 200) return uni.$showMsg('新增计划失败')
        this.updateUserPlanList(res.message)
        return uni.$showMsg('新增计划成功')
      },
      // 调用删除计划接口
      async deletePlanToServer() {
        // 准备参数
        var token = uni.getStorageSync('token')
        const query = {
          token,
          planIndex: this.index,
        };
        const {
          data: res
        } = await uni.$http.post('/api/delete/plan', query)
        if (res.meta.status !== 200) return uni.$showMsg('删除计划失败')
        this.updateUserPlanList(res.message)
      },

      // 写计划事件
      writePlan() {
        this.content = ''
        this.isCompletionStatus = false
      },
    }
  }
</script>

<style lang="scss">
  .example-body {
    border: 1px solid red;
  }

  .header {
    height: 60rpx;
    padding: 20rpx;

    .header-title {
      font-size: 40rpx;
      font-weight: bold;
      color: #fba007;
      float: right;
    }
  }

  .plan-date-box {
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .plan-date {
      color: grey;
      font-size: 28rpx;
      letter-spacing: 1px;
      text-align: center;
    }
  }

  .plan-content-box {
    margin: 30rpx;

    .plan-content-container {
      height: 100%;
      // border: 1px solid black;
    }

    .plan-content {
      font-size: 34rpx;
      width: 100%;
      // border: 1px solid #ccc;
      // padding: 10px;
      box-sizing: border-box;
      letter-spacing: 1px;
      // border: 1px solid yellow;
      // resize: none;
    }
  }

  .footer {
    display: flex;
    flex-direction: row;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    justify-content: space-between;
    align-items: center;
    padding: 10px;

    .footer-icon:first-child {
      width: 30px;
      height: 30px;
    }

    .footer-icon:last-child {
      width: 35px;
      height: 35px;
    }
  }
</style>